import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from google.appengine.dist import use_library
use_library('django', '1.2')

from datetime import datetime, timedelta
from django.utils import simplejson
from google.appengine.api import users, images
from google.appengine.ext import db, webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import settings



class Image(db.Model):
    content = db.BlobProperty()

class Quotation(db.Model):
    author = db.UserProperty()
    content = db.StringProperty(multiline=True)
    date = db.DateTimeProperty(auto_now_add=True)
    year = db.IntegerProperty()
    month = db.IntegerProperty()
    day = db.IntegerProperty()
    picture = db.ReferenceProperty(Image)
    

class MainPage(webapp.RequestHandler):
    def get(self, date):
        today = datetime.today()
        now = today
        if date:
            try:
                now = datetime.strptime(date, settings.URL_DATE_FORMAT)
            except:
                self.redirect('/' + today.strftime(settings.URL_DATE_FORMAT))            
            quotations = Quotation.all().filter('year', now.year).filter('month', now.month).filter('day', now.day).fetch(1)
            if len(quotations) == 0:
                quotations = Quotation.all().filter('date <=', now).order("-date").fetch(1)
                if len(quotations) > 0:
                    self.redirect('/' + quotations[0].date.strftime(settings.URL_DATE_FORMAT))
                else:
                    self.redirect('/')
            prevdate = now + timedelta(days=-1)
            nextdate = now + timedelta(days=1)
            template_values = {
                'quotations': quotations,
                'today': today.strftime(settings.URL_DATE_FORMAT),
                'now': now.strftime(settings.URL_DATE_FORMAT),
                'prevdate': prevdate.strftime(settings.URL_DATE_FORMAT),
                'nextdate': nextdate.strftime(settings.URL_DATE_FORMAT)
                }
            path = os.path.join(os.path.dirname(__file__), 'index.html')
            self.response.out.write(template.render(path, template_values))
        else:
            self.redirect('/' + now.strftime(settings.URL_DATE_FORMAT))
      
      
class ShowImage(webapp.RequestHandler):
    def get(self):
        image = Image.get_by_id(long(self.request.get('id')))
        if image:
            self.response.headers['Content-Type'] = "image/png"
            self.response.headers['Cache-Control'] = "public, max-age=%d" % (365 * 24 * 3600)
            self.response.headers['Last-Modified'] =  (datetime.today()-timedelta(days=365)).strftime('%a, %d %b %Y %H:%M:%S %Z')
            self.response.headers['Expires'] =  (datetime.today()+timedelta(days=365)).strftime('%a, %d %b %Y %H:%M:%S %Z')
            return self.response.out.write(image.content)


class AdminCalendar(webapp.RequestHandler):
    def get(self):
        template_values = { }
        path = os.path.join(os.path.dirname(__file__), 'admin-calendar.html')
        self.response.out.write(template.render(path, template_values))        
        
        
class AdminList(webapp.RequestHandler):
    def get(self):
        quotations_query = Quotation.all().order('-date')
        quotations = quotations_query.fetch(1000)
        newdate = datetime.now()
        if len(quotations) > 0:
            newdate = quotations[0].date + timedelta(days=1)          
        template_values = {
            'quotations': quotations,
            'now': datetime.now(),
            'newdate': newdate
        }
        path = os.path.join(os.path.dirname(__file__), 'admin-list.html')
        self.response.out.write(template.render(path, template_values))        
        
        
class AdminCalendarJSON(webapp.RequestHandler):
    def get(self):
        start = datetime.fromtimestamp(float(self.request.get('start')))
        end = datetime.fromtimestamp(float(self.request.get('end')))
        quotations_query = Quotation.all().filter('date >= ', start).filter('date < ', end);
        quotations = quotations_query.fetch(1000)
        self.response.headers['Content-Type'] = 'application/json'
        jsonData = [] 
        for q in quotations:
            jsonData.append({ 'id': q.key().id(), 'title': q.content, 'start': q.date.isoformat(),
                              'picture': q.picture.key().id() if q.picture else None })
        self.response.out.write(simplejson.dumps(jsonData))
        
        
class AdminSave(webapp.RequestHandler):
    def post(self):
        quotation = Quotation()
        if self.request.get('id'):
            load_id = long(self.request.get('id'))
            quotation = Quotation.get_by_id(load_id)
        if users.get_current_user():
            quotation.author = users.get_current_user()
        quotation.content = self.request.get('content').lstrip().rstrip().lstrip('\n').rstrip('\n')
        if self.request.get('date'):
            quotation.date = datetime.strptime(self.request.get('date'), "%d.%m.%Y")
        else:
            quotation.date = datetime.now()
        quotation.year = quotation.date.year
        quotation.month = quotation.date.month
        quotation.day = quotation.date.day
        picture = self.request.get('picture')
        if picture:
            image = Image()
            picture = images.resize(picture, 1000, 300)
            image.content = db.Blob(picture)
            image.put()
            if quotation.picture:
                db.delete(quotation.picture)
            quotation.picture = image
        quotation.put()
        self.redirect('/admin')


class AdminDelete(webapp.RequestHandler):
    def get(self):
        if self.request.get('id'):
            load_id = long(self.request.get('id'))
            quotation = Quotation.get_by_id(load_id)
            if quotation.picture:
                db.delete(quotation.picture)
            quotation.delete()
        self.redirect('/admin')



application = webapp.WSGIApplication(
                                     [('/show-image', ShowImage),
                                      ('/admin', AdminCalendar),
                                      ('/admin/calendar', AdminCalendarJSON),
                                      ('/admin/list', AdminList),
                                      ('/admin/save', AdminSave),
                                      ('/admin/delete', AdminDelete),
                                      ('/(.*)', MainPage)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()